//
//  SmscodeLoginPage.swift
//  Casecord
//
//  Created by baozi on 2024/1/4.
//

import SwiftUI

struct SmscodeLoginPage: View {
    var phone: String
    var areaCode: String
    var signType: SignType
    var password: String?
    
    @FocusState private var focusState: Bool
    @StateObject var logic: SmscodeLogic = SmscodeLogic()
    var body: some View {
        ZStack {
            Theme.color.primaryBackgroundColor
                .ignoresSafeArea()
            VStack {
                Color.clear.frame(height: 100)
                VStack {
                    Text("Verification code has been send to \n\(phone)")
                        .lineSpacing(8)
                        .foregroundColor(Theme.color.title)
                        .font(.system(size: 20))
                }
                
                OTPTextfield(
                    slot: 6,
                    otp: $logic.otp,
                    isTextFieldFocused: _focusState,
                    onComplete: {
                        focusState = false
                        logic.login()
                    }
                )
                .paddingTop(10)
                
                Button(action: {
                    actionOnSend()
                }, label: {
                    Text(logic.isSending ? "\(logic.countdownSeconds)s" : "Send")
                        .foregroundColor(Theme.color.primaryBackgroundColor)
                        .padding()
                        .paddingHorizontal(20)
                        .withCapsuleBg(colors: [.white], shadow: Color.gray, radius: 10)
                })
                .disabled(logic.isSending)
                .paddingTop(10)
                Spacer()
            }
            .setCustomNav(title: "Smscode Login")
        }
        .onAppear(perform: {
            logic.areaCode = areaCode
            logic.phone = phone
            logic.signType = signType
            logic.password = password
            logic.startTimer()
        })
    }
    
    func actionOnSend() {
        logic.reSendSMS()
    }
    
}

#Preview {
    SmscodeLoginPage(phone: "123456", areaCode: "86", signType: SignType.password_login)
}
